import dingNotify from './dingNotify.js';

/**
 * 工单处理服务
 */
class WorkOrderService {
    /**
     * 创建工单
     * @param {object} workOrderData - 工单数据
     */
    async createWorkOrder(workOrderData) {
        try {
            // 创建工单
            const response = await fetch('/api/workorder/create', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(workOrderData)
            });

            const result = await response.json();
            if (result.success) {
                // 发送钉钉通知给处理人
                await dingNotify.sendWorkOrderCreatedNotify(
                    result.data,
                    workOrderData.assigneeId
                );
            }

            return result;
        } catch (error) {
            console.error('创建工单失败:', error);
            throw error;
        }
    }

    /**
     * 分配工单
     * @param {string} orderId - 工单ID
     * @param {string} assigneeId - 处理人ID
     */
    async assignWorkOrder(orderId, assigneeId) {
        try {
            const response = await fetch(`/api/workorder/assign/${orderId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ assigneeId })
            });

            const result = await response.json();
            if (result.success) {
                // 发送钉钉通知给新处理人
                await dingNotify.sendWorkOrderAssignedNotify(
                    result.data,
                    assigneeId
                );
            }

            return result;
        } catch (error) {
            console.error('分配工单失败:', error);
            throw error;
        }
    }

    /**
     * 完成工单
     * @param {string} orderId - 工单ID
     * @param {object} completeData - 完成信息
     */
    async completeWorkOrder(orderId, completeData) {
        try {
            const response = await fetch(`/api/workorder/complete/${orderId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(completeData)
            });

            const result = await response.json();
            if (result.success) {
                // 发送钉钉通知给工单创建人
                await dingNotify.sendWorkOrderCompletedNotify(
                    result.data,
                    result.data.creatorId
                );
            }

            return result;
        } catch (error) {
            console.error('完成工单失败:', error);
            throw error;
        }
    }
}

export default new WorkOrderService(); 